import { onBeforeUnmount, shallowRef, reactive, onMounted, ref } from 'vue'
import * as qiniu from 'qiniu-js'
import { qiniuCDN } from '@/http'
import { getQiniuTokenApi } from '@/http/api/site'
import { qiniuUploadImage, qiniuUploadVideo } from '@/http/qiniu'
import { ElMessage } from 'element-plus'


type InsertImageType = (url: string, alt: string, href: string) => void
type InsertVideoType = (url: string) => void

export default function useWangEditor() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const toolbarConfig = {}
    const editorConfig = {
        placeholder: '请输入内容...',
        MENU_CONF: {}
    }
    // 自定义上传图片
    editorConfig.MENU_CONF['uploadImage'] = {
        allowedFileTypes: ['image/*'],
        base64LimitSize: 8 * 1024,
        customUpload(file: File, insertFn: InsertImageType) {
            getQiniuTokenApi().then(res => {
                if (res && res.code == 200) {
                    const options = {
                        quality: 0.92,
                        noCompressIfLarger: true,
                    }
                    qiniu.compressImage(file, options).then(cFile => {
                        qiniuUploadImage(cFile.dist as File, res.data.token).subscribe({
                            next(res) {
                                editorRef.value.showProgressBar(res.total.percent)
                            },
                            error(err) {
                                ElMessage.warning('上传出错,请重新再上传!')
                            },
                            complete(res) {
                                insertFn(qiniuCDN + res.key, '', qiniuCDN + res.key)
                            }
                        })
                    })
                }
            })

        }
    }
    // 自定义上传视频
    editorConfig.MENU_CONF['uploadVideo'] = {
        customUpload(file: File, insertFn: InsertVideoType) {
            getQiniuTokenApi().then(res => {
                if (res && res.code == 200) {
                    qiniuUploadVideo(file as File, res.data.token).subscribe({
                        next(res) {
                            editorRef.value.showProgressBar(res.total.percent)
                        },
                        error(err) {
                            ElMessage.warning('上传出错,请重新再上传!')
                        },
                        complete(res) {
                            insertFn(qiniuCDN + res.key)
                        }
                    })
                }
            })

        }
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor) => {
        editorRef.value = editor
    }

    return { editorRef, mode: 'default', toolbarConfig, editorConfig, handleCreated }
}